<?php
/**
 * Created by PhpStorm.
 * User: jiangtaiping
 * Date: 2017/2/23
 * Time: 11:39
 */
class Service_Manager{

    /**
     * 获取后台账号信息
     * @param int $uid 指定的账号ID
     * @return array
     */
    public static function getInfoById($uid=0)
    {
        if($uid == 0){
            return array();
        }
        $cacheKey = "manager-info-" . $uid;
        $cacheValue = FCache::get($cacheKey);
        if ($cacheValue){
            return $cacheValue;
        }
        $managerTable = new FTable('manager');
        $managerData = $managerTable->where(array('uid' => $uid))->find();
        FCache::set($cacheKey, $managerData,86400);
        return $managerData;
    }

    public static function clearInfoById($uid=0){
        $cacheKey = "manager-info-" . $uid;
        FCache::delete($cacheKey);
        self::getInfoById($uid);
    }
    /**
     * 获取当前用户的信息和状态
     * @return array|bool
     */
    public static function getSessionData()
    {
        global $_F;
        $auth_str = FCookie::get('manager_auth');
        list($uid, $auth) = explode("\t", $auth_str);

        if (!$auth) {
            return false;
        }

        $check_auth = null;
        $managerTable = new FTable('manager');

        $managerData = $managerTable->where(array('uid' => $uid))->find();
        if ($managerData) {
            $check_auth = md5("{$managerData['username']}|{$managerData['password']}|{$managerData['groupid']}");
        }

        if ($check_auth == $auth) {
            $_F['member'] = $managerData;
            $_F['uid'] = $uid;
            $_F['gid'] = $managerData['gid'];
            return $managerData;
        }
        FCookie::set('manager_auth', '', -1,$_F['http_host']);
        return false;
    }

    /**
     * 移除当前账号的认证cookie
     */
    public static function removeSession()
    {
        global $_F;
        FCookie::set('manager_auth', '', -1);
    }

    /**
     * 批量处理权限值
     * @param array $permission
     * @return array
     */
    public static function batchCheckRole($permission){
        $new_permission = array();
        foreach ($permission as $k=>$v){
            $new_permission[$k] = self::checkRole($v);
        }
        return $new_permission;
    }

    /**
     * 检测是否有权限访问一个地址
     * @param string $url 要访问的方法，为空时自动获取当前的方法
     * @return bool
     */
    public static function checkRole($url = '',$gid=0){
        global $_F;
        if(!$gid){
            $gid = $_F['member']['groupid'];
        }
        $groupRole = self::getGroupRole($gid);
//        var_dump($gid);
//        var_dump($groupRole);exit();
        /**
         * 如果当前组是超级管理员组，直接全部通过
         */
        if($gid == FConfig::get('global.super_gid') || in_array('is_super_manager',$groupRole['permission'])){
            return true;
        }
        if($url == ''){
            $url = '/'.$_F['module'].'/'.str_replace('controller_'.$_F['module'].'_','',strtolower($_F['controller'])).'/'.$_F['action'];
        }
        $url = strtolower($url);
        if(in_array($url,$groupRole['permission'])){
            return true;
        }
        return false;
    }

    public static function getGroupRole($gid){
        $cache_key = 'admin_group_cache_new_'.$gid;
        $Role = FCache::get($cache_key);
        if(!$Role){
            $groupTable = new FTable('manager_group');
            $roleData = $groupTable->fields('permission')->where(array('id'=>$gid))->find();
            if($roleData){
                $Role = unserialize($roleData['permission']);
            }else{
                $Role = array();
            }
            /**
             * 开发时给所有的权限
             * $permission = FConfig::get('permission');
             * $Role = array_keys($permission);
             */
            /**
             * 补充基本拥有的界面权限
             */
            $basic = FConfig::get('permission.basic');
            $Role = array_merge($Role,$basic);
            FCache::set($cache_key,$Role,30*86400);
        }
        return $Role;
    }

    /**
     * 更新用户组权限缓存
     * @param int $gid 组id
     */
    public static function clearGroupRole($gid){
        $cache_key = 'admin_group_cache_new_'.$gid;
        FCache::delete($cache_key);
        self::getGroupRole($gid);
    }

    /**
     * 获取加密后的密码
     * @param string $password 密码
     * @return string
     */
    public static function getEncryptPassword($password)
    {
        return md5($password);
    }

    /**
     * 写入一条后台操作日志
     * @param string $action 日志事件
     * @param string $comment 事件详细描述
     * @param int $mid 管理员ID
     * @return bool
     */
    public static function addManagerLog($action='',$comment='',$mid=0){
        global $_F;
        if($action == "" && $comment == "") return false;
        if($mid == 0){
            $mid = isset($_F['uid']) ? $_F['uid'] : 0;
        }
        $logTable = new FTable('manager_log');
        $logTable->insert(array(
            'action'=>$action,
            'comment'=>$comment,
            'mid'=>$mid,
            'create_time'=>CURRENT_DATE_TIME,
            'ip'=>FRequest::getClientIP()
        ));
        return true;
    }

    /**
     * 获取下属的拓展员ID
     * @param int $uid
     * @return array
     */
    public static function getChilderUserId($uid=0){
        global $_F;
        $uids = array();
        if($uid == 0){
            $uid = $_F['uid'];
        }
        $userInfo = self::getInfoById($uid);
        /**
         * 组长类型的账号，取出下属组员ID
         */
        if($userInfo['account_type'] == 3){
            $userTable = new FTable('manager');
            $userList = $userTable->fields('uid')->where(array('parent_id'=>$uid))->select();
            $uids[] = $_F['uid'];
            foreach ($userList as $v){
                $uids[] = $v['uid'];
            }
        }
        /**
         * 管理员类型，不限制下属
         */
        if($userInfo['account_type'] == 1){
            $uids = array();
        }
        /**
         * 拓展员类型，只显示自己的
         */
        if($userInfo['account_type'] == 2){
            $uids = array($uid);
        }
        return $uids;
    }

    /**
     * 随机取一个QQ号码
     */
    public static function getRandUserQQ(){
        $cache_key = 'manager_qq_list';
        $qqlist = FCache::get($cache_key);
        if(!$qqlist){
            $userTable = new FTable('manager');
            $userList = $userTable->fields('qq')->where(array('account_type'=>2,'status'=>1,'LENGTH(qq)'=>array('gt'=>0)))->select();
            $qqlist = array();
            foreach ($userList as $v){
                $qqlist[] = $v['qq'];
            }
            if(count($qqlist) == 0){
                $qqlist = explode(',',FConfig::get('global.qq_list'));
            }
            FCache::set($cache_key,$qqlist,86400);
        }
        return $qqlist[rand(0,count($qqlist)-1)];
    }
}
